﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using WpfBehaviorDemo.Models;

namespace WpfBehaviorDemo.Behaviors
{
    public class CanvasEllementMoveBehavior : Behavior<UIElement>
    {
        private bool _isMouseDown = false;

        private Canvas _parrentCanvas;

        //返回鼠标指针相对于指定元素的位置。
        private Point _offset = new Point(0, 0);

        protected override void OnAttached()
        {
            AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
            _parrentCanvas = VisualTreeHelper.GetParent(this.AssociatedObject) as Canvas;

            base.OnAttached();
        }

        //左键按下
        private void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //父类存在性判空
            if (_parrentCanvas == null)
                return;

            _isMouseDown = true;
            _offset = e.GetPosition(AssociatedObject);

            //将鼠标的输入事件（如鼠标移动、鼠标释放等）强制绑定到当前控件,避免多控件重叠时鼠标控制权转移的情况
            AssociatedObject.CaptureMouse();
            AssociatedObject.MouseMove += AssociatedObject_MouseMove;
            AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp;
        }

        private void AssociatedObject_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (_isMouseDown)
            {
                var pos = e.GetPosition(_parrentCanvas);//获取鼠标相对于画布的位置
                Canvas.SetLeft(this.AssociatedObject, pos.X - _offset.X);//补正
                Canvas.SetTop(this.AssociatedObject, pos.Y - _offset.Y);
            }
        }

        private void AssociatedObject_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _isMouseDown = false;
            AssociatedObject.ReleaseMouseCapture();//释放鼠标捕获
        }

        protected override void OnDetaching()
        {
            AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;

            base.OnDetaching();
        }

    }
}
